package main

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"os"
)

// Get
// get请求URL参数
func Get(request *http.Request) map[string]string {
	var result = make(map[string]string)
	keys := request.URL.Query()
	for k, v := range keys {
		result[k] = v[0]
	}

	return result
}

// ParseForm
// POST获取form表单参数
func ParseForm(request *http.Request) map[string]string {
	var result = make(map[string]string)
	request.ParseForm()
	for k, v := range request.PostForm {
		if len(v) < 1 {
			continue
		}

		result[k] = v[0]
	}

	return result
}

// ParseJson
// POST获取json参数
func ParseJson(request *http.Request, obj interface{}) error {
	body, err := ioutil.ReadAll(request.Body)
	if err != nil {
		return err
	}

	err = json.Unmarshal(body, obj)
	if err != nil {
		return err
	}

	return nil
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
